import { EntityManager, Knex, MikroORM, QueryBuilder, knex } from '@mikro-orm/mysql';
import { InjectEntityManager, InjectMikroORM } from '@mikro-orm/nestjs';
import { Body, Controller, Get, Post, Query, Req } from '@nestjs/common';
import { Users } from "@entities/Users";
import { JobTasks } from "@entities/JobTasks";
import dayjs from 'dayjs';
import { JobUserConcerns } from "@entities/JobUserConcerns";
import { ApiTags } from '@nestjs/swagger';
import { OrderJobEnrolls } from "@entities/OrderJobEnrolls";

import { knext } from 'knext';
 
import { JobProjectSources } from "@entities/JobProjectSources";
import { JobProjectJobs } from "@entities/JobProjectJobs";
import { JsonApiResponse } from '@utils/json.api.response';
import { knexPrefix } from "@databases/vo/dao-helper";
import { JobTaskVO } from "@databases/vo/JobTasksVO";
import { OrderJobEnrollsVO } from '@databases/vo/OrderJobEnrollersVO';
import { request } from 'http';

@ApiTags('(用户) 兼职-报名')
@Controller('enroll')
export class EnrollsController {
    constructor(
        @InjectMikroORM('zp')
        private readonly orm : MikroORM,
        @InjectEntityManager('zp')
        private readonly em : EntityManager
    ){}

    @Post('create')
    async create(
            @Req() request,
            @Body('job_project_id') job_task_id,
            @Body('expected_job_id') expected_job_id,
    ){
        let user_id = request.user.id

        let knex = knext(this)

        let task =  await  knex.fromORM(JobProjectJobs).where({id:expected_job_id}).getOne()

        if(!task || task.task_id != job_task_id)
        {
            return JsonApiResponse.ERR('职位ID错误')
        }

        let enroll = await knex.fromORM(OrderJobEnrolls)
        .findOrCreate([
            'id',
            'enroller_id',
            'job_task_id',
        ],{
            'enroller_id':user_id,
            'job_task_id':job_task_id,
        },{
            'enroller_id':user_id,
            'job_task_id':job_task_id,
            'expected_job_id':expected_job_id
        })


        let enrolls = await knex.fromORM(OrderJobEnrolls)
        .selectAll()
        //.withEntity(JobProjectSources,'source')
        .withEntity(JobProjectJobs,'expectedJob')
        .where({id:enroll[0].id})
        .populate()
    
        return JsonApiResponse.object(enrolls)
    }

    @Get('list')
    public async list(@Req() request : Request, @Query('type') type) {
        const userId = (request['user'] as Users).id;

        const knex = knext(this);

        const name = knex.tableName(JobTasks)

        const qb =  knex
        .fromORM(OrderJobEnrolls)
        .select('*')
        .leftJoin(
            knex.tableRaw(JobTasks),
            knex.tableField(OrderJobEnrolls,'job_task_id'),
            '=',
            knex.tableField(JobTasks,'id'))
        .where('enroller_id','=',userId)
        .withEntity(JobTasks,'jobTask',(qb)=>{
            qb.onlySelect(...knexPrefix(JobTaskVO.baseInfo()))
            .withEntity(JobProjectSources,'source',(qb)=>{
                qb.onlySelect('title')
            })
        },'project')
        .withEntity(JobProjectJobs,'expectedJob')
        .map((entity)=>{
            entity.state_step = OrderJobEnrollsVO.calcStepStatus(entity)
            entity.project.title = entity.project.source.title
            return entity
        })
        .filter(()=>{
            return true
        })

        let date = dayjs().add(-3,'day').format('YYYY-MM-DD');

        if(type == 'recent')
        {
            qb.andWhere('start_date','>=',date)
        }
        else if(type == 'history')
        {
            qb.andWhere('start_date','<',date)
        }

        qb.orderBy('start_date','desc')
        
        let results = await qb.populate()

        return JsonApiResponse.new(results);        
    }
}
